import pygame
from pygame.locals import *
import requests
import json

class LoginScene:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.font = pygame.font.Font(None, 32)
        self.small_font = pygame.font.Font(None, 24)
        
        # 输入框
        self.username_input = pygame.Rect(width//2-100, height//2-50, 200, 30)
        self.password_input = pygame.Rect(width//2-100, height//2, 200, 30)
        
        # 按钮
        self.login_btn = pygame.Rect(width//2-100, height//2+50, 90, 40)
        self.register_btn = pygame.Rect(width//2+10, height//2+50, 90, 40)
        
        # 文本
        self.username_text = ""
        self.password_text = ""
        self.active_input = None
        self.message = ""
        self.message_color = (255, 0, 0)
        
        # 光标相关
        self.cursor_visible = True
        self.cursor_timer = 0
        self.cursor_blink_time = 500  # 光标闪烁间隔（毫秒）
        
    def draw(self, screen):
        screen.fill((240, 240, 240))
        
        # Draw title
        title = self.font.render("Pokemon Battle - Login/Register", True, (0, 0, 0))
        screen.blit(title, (self.width//2 - title.get_width()//2, self.height//4))
        
        # Draw input boxes
        pygame.draw.rect(screen, (255, 255, 255), self.username_input)
        pygame.draw.rect(screen, (255, 255, 255), self.password_input)
        
        # Draw input labels
        username_label = self.small_font.render("Username:", True, (0, 0, 0))
        screen.blit(username_label, (self.username_input.x - 70, self.username_input.y + 5))
        
        password_label = self.small_font.render("Password:", True, (0, 0, 0))
        screen.blit(password_label, (self.password_input.x - 70, self.password_input.y + 5))
        
        # Draw input text
        # 绘制输入文本和光标
        if self.active_input == "username":
            text_surface = self.font.render(self.username_text, True, (0, 0, 0))
            screen.blit(text_surface, (self.username_input.x + 5, self.username_input.y + 5))
            if self.cursor_visible:
                cursor_x = self.username_input.x + 5 + text_surface.get_width()
                pygame.draw.line(screen, (0, 0, 0),
                               (cursor_x, self.username_input.y + 5),
                               (cursor_x, self.username_input.y + 25))
        else:
            username_surface = self.font.render(self.username_text, True, (0, 0, 0))
            screen.blit(username_surface, (self.username_input.x + 5, self.username_input.y + 5))
            
        if self.active_input == "password":
            password_surface = self.font.render("*" * len(self.password_text), True, (0, 0, 0))
            screen.blit(password_surface, (self.password_input.x + 5, self.password_input.y + 5))
            if self.cursor_visible:
                cursor_x = self.password_input.x + 5 + password_surface.get_width()
                pygame.draw.line(screen, (0, 0, 0),
                               (cursor_x, self.password_input.y + 5),
                               (cursor_x, self.password_input.y + 25))
        else:
            password_surface = self.font.render("*" * len(self.password_text), True, (0, 0, 0))
            screen.blit(password_surface, (self.password_input.x + 5, self.password_input.y + 5))
        
        # 更新光标闪烁
        current_time = pygame.time.get_ticks()
        if current_time - self.cursor_timer > self.cursor_blink_time:
            self.cursor_visible = not self.cursor_visible
            self.cursor_timer = current_time
        
        # Draw buttons
        pygame.draw.rect(screen, (100, 200, 100), self.login_btn)
        pygame.draw.rect(screen, (100, 150, 200), self.register_btn)
        
        login_text = self.font.render("Login", True, (255, 255, 255))
        screen.blit(login_text, (self.login_btn.x + 25, self.login_btn.y + 10))
        
        register_text = self.font.render("Register", True, (255, 255, 255))
        screen.blit(register_text, (self.register_btn.x + 25, self.register_btn.y + 10))
        
        # Draw message
        if self.message:
            msg_surface = self.small_font.render(self.message, True, self.message_color)
            screen.blit(msg_surface, (self.width//2 - msg_surface.get_width()//2, self.height//2 + 100))
    
    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.login_btn.collidepoint(event.pos):
                return self.login()
            elif self.register_btn.collidepoint(event.pos):
                return self.register()
            elif self.username_input.collidepoint(event.pos):
                self.active_input = "username"
            elif self.password_input.collidepoint(event.pos):
                self.active_input = "password"
            else:
                self.active_input = None
        elif event.type == pygame.KEYDOWN and self.active_input:
            if event.key == K_BACKSPACE:
                if self.active_input == "username":
                    self.username_text = self.username_text[:-1]
                else:
                    self.password_text = self.password_text[:-1]
            else:
                if self.active_input == "username":
                    self.username_text += event.unicode
                else:
                    self.password_text += event.unicode
    
    def login(self):
        try:
            response = requests.post(
                "http://localhost:5000/login",
                json={"username": self.username_text, "password": self.password_text}
            )
            data = response.json()
            
            if data["success"]:
                self.message = "Login successful"
                return True, data["game_data"]
            else:
                self.message = data["message"]
                return False, None
        except Exception as e:
            self.message = "Cannot connect to server"
            return False, None
    
    def register(self):
        try:
            response = requests.post(
                "http://localhost:5000/register",
                json={"username": self.username_text, "password": self.password_text}
            )
            data = response.json()
            
            if data["success"]:
                self.message = "Registration successful, please login"
                return True, None
            else:
                self.message = data["message"]
                return False, None
        except Exception as e:
            self.message = "Cannot connect to server"
            return False, None